package com.zaker.touchtv.modules.polling;

import android.app.job.JobParameters;
import android.app.job.JobService;
import android.os.Build;
import android.os.Looper;
import android.os.PersistableBundle;
import android.support.annotation.RequiresApi;
import android.util.Log;

import com.zaker.touchtv.utils.Constants;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by Zonda on 2016/10/26. 用来处理定时任务
 */

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class PollSingleSchedulerService extends JobService {

  private final String LOG_TAG = "PollSingle";

  private ThreadPoolExecutor mPollExecutor;

  public final static String UID_KEY = "uid_key";
  public final static String USER_NAME_KEY = "user_name_key";
  public final static String STAT_KEY = "stat_key";

  private long mLastInterval = System.currentTimeMillis();

  @Override
  public boolean onStartJob(final JobParameters params) {

    Log.i(LOG_TAG, "onStartJob is run  intervalMillSeconds: " + intervalMillSeconds());

    initPollExecutor();

    final PersistableBundle persistableBundle = params.getExtras();
    final String uid = persistableBundle.getString(UID_KEY);
    final String userName = persistableBundle.getString(USER_NAME_KEY);
    @Constants.LiveState
    final int stat = persistableBundle.getInt(STAT_KEY);
    mPollExecutor.execute(new Runnable() {
      @Override
      public void run() {

        Log.i(LOG_TAG, "onStartJob uid: " + uid
            + " userName: " + userName + " stat: " + stat
            + " isMainLooper: " + (Looper.myLooper() == Looper.getMainLooper()));

        jobFinished(params, true);

//        AppApiClient.getLiveService().sendClientLiveState(TestDataUtils.CREATE_LIVE_URL,
//            uid, userName, stat);
      }
    });
    return true;
  }

  @Override
  public boolean onStopJob(JobParameters params) {

    Log.i(LOG_TAG, "onStopJob is run ");

    destroyPollExecutor();

    return true;
  }

  private long intervalMillSeconds() {

    if (mLastInterval > 0) {
      return System.currentTimeMillis() - mLastInterval;
    }
    return 0;
  }

  private void initPollExecutor() {

    if (mPollExecutor != null) {
      return;
    }
    mPollExecutor = new ThreadPoolExecutor(1, 1, 1, TimeUnit.MINUTES,
        new LinkedBlockingQueue<Runnable>(),
        Executors.defaultThreadFactory(),
        new ThreadPoolExecutor.DiscardPolicy());
  }

  private void destroyPollExecutor() {

    if (mPollExecutor == null) {
      return;
    }
    mPollExecutor.shutdownNow();
    mPollExecutor = null;
  }
}
